// import { login, getInfo } from '@/api/user'
import { DictListPost } from '@/api'
import { setToken, removeToken } from '@/utils/auth'
import store from '@/store'

const getDefaultState = () => {
  return {
    name: '',
    avatar: '',
    dictList: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_DICTLIST(state, payload) {
    state.dictList = payload
  }
}

const actions = {
  // user login
  async initDictAction({ commit }) {
    const result = await DictListPost({ param: {}})
    commit('SET_DICTLIST', result.recordList)
  },
  login({ commit }, record) {
    const { userName, avatar, userId } = record
    commit('SET_NAME', userName)
    commit('SET_AVATAR', avatar)
    setToken('useLogin', userName)
    sessionStorage.setItem('isLogin', true)
    sessionStorage.setItem('userId', userId)
    store.dispatch('routes/changeRoutes')
  },

  // get user info
  getInfo({ commit, state }) {
    // return new Promise((resolve, reject) => {
    //   getInfo(state.token).then(response => {
    //     const { data } = response

    //     if (!data) {
    //       return reject('Verification failed, please Login again.')
    //     }

    //     const { name, avatar } = data

    //     commit('SET_NAME', name)
    //     commit('SET_AVATAR', avatar)
    //     resolve(data)
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // user logout
  logout({ commit, dispatch, state }) {
    commit('RESET_STATE')
    commit('CHANGE_ROUTES', [])
    dispatch('tagsView/delAllViews', null, { root: true })
    removeToken('useLogin')
    sessionStorage.clear()
    location.reload()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

